﻿var url = "http://localhost:8080/uuticket/flight/queryAirportAction.action";
var pageHref, leftArrow, rightArrow, bShowPaginator, currentPage, pageCount, minPage, maxPage, pageLinkCount, halfLinkCount;
var firsttime, lasttime, timeout, cityItemsNum, currHighlightId, maxIndex, minIndex, childs, queryStr, ddType;
var highlightClass = "deyboard";
var selectedClass = "hover";
var commonClass = "a1";
var currPageLinkClass = "address_current";

var tipMessage = {
  helpMsg: "输入中文/拼音/英文或↑↓选择", 
  findMsg: "%s, 按拼音排序", 
  notFindMsg: "对不起，找不到：%s"
};
var qualifiedAirport=[];
var currShowAirport=[];
var bLoadAirport = false;

function initAirport() {
  $.getJSON(url, function(data){
    airport = data.airports;
    bLoadAirport = true;
  });
}

function initialize() {
  childs = getAddrArr();
  timeout = -1;
  cityItemsNum = 12;
  currHighlightId = -1;
  maxIndex = -1;
  minIndex = -1;
  bShowPaginator = false;
  currentPage = 0;
  pageCount = 0;
  minPage = 0;
  maxPage = 0;
  pageLinkCount = 5;
  halfLinkCount = 2;
  pageHref = $("a[id^='address_p']");
  leftArrow = $("#address_arrowl");
  rightArrow = $("#address_arrowr");
}

function initEvent(){
  $(childs).each(function(index) {
    $(this).mouseover(function(){
      var display = this.style.display;
      if(display == 'block') {
        this.cssClass = selectedClass;
        currHighlightId = index;
      }
    });
    
    $(this).mouseout(function(){
      var display = this.style.display;
      if(display == 'block') {
        this.cssClass = commonClass;
      }
    });
    
    $(this).click(function(objEvent){
      objEvent.preventDefault();
      currHighlightId = index;
      _fillTextbox(this);
    });
  });
  
  $("#" + ddType + "Id").bind('blur', function(){
    closeTip();
  });
  
  $("#tuna_address").mouseenter(function(){
    $("#" + ddType + "Id").unbind("blur");
  });
  $("#tuna_address").mouseleave(function(){
    $("#" + ddType + "Id").bind("blur", function(){
      closeTip();
    });
  });
}

function initPara() {
}

function _fillTextbox(selAdd) {
  var re = currShowAirport[currHighlightId];
  $("#" + ddType + "Id").val(re.city);
  $("#" + ddType + "CodeId").val(re.code);
  closeTip();
}

function showTip(event, type) {
  
  var keyCode  = event.keyCode;
  if((keyCode > 8 && keyCode < 13) || (keyCode > 13 && keyCode < 32) || (keyCode > 32 && keyCode < 38) || keyCode == 39 || (keyCode > 40 && keyCode < 46) || keyCode == 47 || keyCode > 111) {
    return;
  }
  ddType = type;
  if(keyCode == 38 || keyCode == 40) {
    // move up and down to select
    var up = (keyCode == 38 ? true : false);
    moveByArrow(up);
    return;
  }
  
  if(keyCode == 13) {
    // enter the value
    if(currHighlightId >= minIndex && currHighlightId <= maxIndex) {
      var node = childs[currHighlightId];
      _fillTextbox(node);
    }
    return;
  }
  
  var now = new Date();
  if(!firsttime) {
    firsttime = now;
    lasttime = now;
  } else {
    firsttime = lasttime;
    lasttime = now;
  }
  if(lasttime - firsttime < 100) {
    clearTimeout(timeout);
    timeout = setTimeout(function(){
      
      var now2 = new Date();
      var cha = now2 - lasttime;
      if(cha > 90) {
        firsttime = null;
        lasttime = null;
        
        popupTip();
      } else {
      }
    }, 100);
  }
}

function closeTip() {
  if(currHighlightId != -1) {
    childs[currHighlightId].cssClass = commonClass;
  }
  
  firsttime = null;
  lasttime = null;
  currHighlightId = -1;
  minIndex = -1;
  maxIndex = -1;
  
  $("#tuna_address").css("display", "none");
  
  // unbind the event listener
  $("#" + ddType + "Id").unbind("blur");
  $(childs).each(function(index, ele) {
    $(ele).unbind("mouseover");
    $(ele).unbind("mouseout");
    $(ele).unbind("click");
  });
}

function moveByArrow(up) {
  if(!up) {
    currHighlightId ++;
    if(currHighlightId > maxIndex) {
      currHighlightId = currHighlightId - maxIndex - 1;
    }
  } else {
    currHighlightId --;
    if(currHighlightId < 0) {
      currHighlightId = maxIndex;
    }
  }
  
  if(up) {
    var prevId = currHighlightId + 1;
    if(prevId > maxIndex) {
      prevId = 0;
    }
  } else {
    var prevId = currHighlightId - 1;
    if(prevId < 0) {
      prevId = maxIndex;
    }
  }
  $(childs[prevId]).removeClass().addClass(commonClass);
  $(childs[currHighlightId]).removeClass().addClass(highlightClass);
}

function popupTip(type) {
  if(type) {
    ddType = type;
  }
  
  if(bLoadAirport) {
    _popupTip();
  } else {
    var input = $("#" + ddType + "Id");
    input.attr("disabled", "disabled");
    input.val("Loading...");
    timeout2 = setInterval(function(){
      if(bLoadAirport) {
        clearInterval(timeout2);
        input.val("");
        input.removeAttr("disabled");
        _popupTip();
      }
    }, 100);
  }
}

function _popupTip() {
  //if(timeout2) clearInterval(timeout2);
  initEvent();
  //var inputCtl = $("#" + ddType + "Id")[0];
  var inputText = $("#" + ddType + "Id").val().trim();
  queryStr = inputText;
  qualifiedAirport =  _filterData(inputText);
  visibleAndMoveTip();
  showMsg();
  currentPage = 0;
  currHighlightId = -1;
  popupData(qualifiedAirport.slice(0, cityItemsNum), inputText);
  initPaginator();
  showPaginator();
}

function showMsg() {
  var msgDiv = $("#address_message");
  if(qualifiedAirport.length == 0) {
    msgDiv.html(tipMessage.notFindMsg.replace("%s", queryStr.trim()));
  } else if(queryStr.trim() == '') {
    msgDiv.html(tipMessage.helpMsg);
  } else {
    msgDiv.html(tipMessage.findMsg.replace("%s", queryStr.trim()));
  }
}

function initPaginator(){
  if(qualifiedAirport.length <= cityItemsNum) {
    bShowPaginator = false;
  } else {
    pageCount = Math.ceil(qualifiedAirport.length / cityItemsNum);
    if(pageCount == 1) {
      bShowPaginator = false;
    } else {
      bShowPaginator = true;
      minPage = Math.max(0, currentPage - halfLinkCount);
      if(pageCount > pageLinkCount) minPage = Math.min(minPage, pageCount - pageLinkCount);
      maxPage = Math.min(minPage + pageLinkCount - 1, pageCount - 1);
    }
  }
}

function showPaginator() {
  if(!bShowPaginator) {
    $("#address_p").css("display", "none");
    return;
  }
  buildPaginator();
  
  $("#address_p").css("display", "block");
}

function stopDefault(e) {
  if ( e && e.preventDefault ) {
    e.preventDefault();
  } else {
    e.returnValue = false;
    return false;
  }
}

function buildPaginator() {
  if(currentPage == minPage) {
    leftArrow.css("display", "none");
  } else {
    leftArrow.removeAttr("style");
  }
  
  if(currentPage == maxPage) {
    rightArrow.css("display", "none");
  } else {
    rightArrow.removeAttr("style");
  }
  
  $(pageHref).each(function(index){
    if((index + minPage) == currentPage) {
      $(this).removeClass().addClass(currPageLinkClass);
    } else {
      $(this).removeClass();
    }
    if(index > maxPage - minPage) {
      $(this).css("display", "none");
    } else {
      $(this).removeAttr("style");
      $(this).html(minPage +index + 1);
    }
  });
}

function clickPrevPage(e) {
  prevPage();
  return stopDefault(e);
}

function clickNextPage(e) {
  nextPage();
  return stopDefault(e);
}

function clickPageLink(e, ctl) {
  clickPage($(ctl).html()-1);
  return stopDefault(e);
}

function clickPage(page) {
  currentPage = page;
  _pageChange();
}

function nextPage() {
  currentPage ++;
  if(currentPage < pageCount) {
    _pageChange();
  }
}

function prevPage() {
  currentPage --;
  if(currentPage >= 0) {
    _pageChange();
  }
}

function _pageChange() {
  minIndex = -1;
  maxIndex = -1;
  currHighlightId = -1;
  popupData(qualifiedAirport.slice(currentPage * cityItemsNum, (currentPage + 1) * cityItemsNum), queryStr);
  initPaginator();
  buildPaginator();
  var tempType = new String(ddType);
  $("#" + tempType + "Id").die('focus');
  $("#" + tempType + "Id").trigger('focus');
  $("#" + tempType + "Id").live('focus', function(){popupTip(tempType);});
}

function _filterData(inputText) {
  var it = inputText.toLowerCase();
  return $.grep(airport || [], function(v, index){
    return (v.code && v.code.toLowerCase().indexOf(it) == 0) || (v.city && v.city.indexOf(inputText) == 0) || (v.cityEngName && v.cityEngName.toLowerCase().indexOf(it) == 0)
  });
}

function visibleAndMoveTip() {
  $("#tuna_address").
    css("left", $("#" + ddType + "Id").position().left + "px").
    css("top", ($("#" + ddType + "Id").position().top + $("#" + ddType + "Id").outerHeight()) + "px").
    css("display", "block");
}

function popupData(showData, inputText) {
  currShowAirport = showData;
  var bHighlight = false;
  $(childs).each(function(index){
    if(showData[index]) {
      this.style.display = "block";
      if(inputText && inputText.trim() != "" && !bHighlight && (inputText == showData[index].code || inputText == showData[index].city)) {
        $(this).removeClass().addClass(highlightClass);
        currHighlightId = index;
        bHighlight = true;
      } else {
        $(this).removeClass().addClass(commonClass);
      }
      $(this).html("<span>" + showData[index].cityEngName + "</span>" + showData[index].city);
    } else {
      this.style.display = "none";
      $(this).removeClass().addClass(commonClass);
    }
  });
  
  maxIndex = showData.length - 1;
  if(maxIndex >= 0) {
    minIndex = 0;
  }
}

function _getValue(node) {
  return {value: node.childNodes[0].innerHTML, name: node.childNodes[1] ? node.childNodes[1].nodeValue : node.childNodes[0].innerHTML};
}

function getAddrArr () {
  return $("#address_list a");
}

function _outputTime(date) {
  return date.getMinutes() + ":" + date.getSeconds() + "." + date.getMilliseconds();
}

initAirport();